<template>
  <div class="projects-container">
    <!-- 页面标题和统计信息 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">项目管理</h2>
        <div class="stats-section">
          <div class="stat-item">
            <span class="stat-value">{{ filteredProjects.length }}</span>
            <span class="stat-label">项目总数</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ getActiveProjectsCount() }}</span>
            <span class="stat-label">进行中</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ getCompletedProjectsCount() }}</span>
            <span class="stat-label">已完成</span>
          </div>
        </div>
      </div>
      <div class="action-section">
        <el-button type="primary" icon="el-icon-plus" @click="showDialog = true">新增项目</el-button>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="filter-bar">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索项目名称或描述"
          clearable
          prefix-icon="el-icon-search"
          class="search-input"
        />
      </div>
      <div class="filter-section">
        <el-select v-model="status" placeholder="项目状态" class="filter-select">
          <el-option label="全部项目" value="" />
          <el-option label="进行中" value="active" />
          <el-option label="已完成" value="completed" />
          <el-option label="已暂停" value="paused" />
        </el-select>
        <el-select v-model="sortBy" placeholder="排序方式" class="filter-select">
          <el-option label="创建日期" value="createDate" />
          <el-option label="截止日期" value="deadline" />
          <el-option label="完成进度" value="progress" />
        </el-select>
        <el-button-group class="view-toggle">
          <el-button :class="{ active: viewMode === 'card' }" @click="viewMode = 'card'">
            <i class="el-icon-s-grid"></i>
          </el-button>
          <el-button :class="{ active: viewMode === 'list' }" @click="viewMode = 'list'">
            <i class="el-icon-menu"></i>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 项目列表 - 卡片视图 -->
    <el-row :gutter="20" class="project-list" v-if="viewMode === 'card'">
      <el-col :span="8" v-for="project in sortedProjects" :key="project.id">
        <el-card shadow="hover" class="project-card" :class="'status-' + project.status">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-tag :type="getStatusType(project.status)" effect="dark">{{ project.statusText }}</el-tag>
                <h3 class="project-title">{{ project.name }}</h3>
              </div>
              <div class="header-right">
                <el-dropdown trigger="click">
                  <i class="el-icon-more"></i>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="viewProjectDetail(project.id)">查看详情</el-dropdown-item>
                      <el-dropdown-item @click="editProject(project)">编辑项目</el-dropdown-item>
                      <el-dropdown-item @click="changeStatus(project)">更改状态</el-dropdown-item>
                      <el-dropdown-item @click="deleteProject(project)" class="danger">删除项目</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
          <div class="card-content">
            <p class="description">{{ project.description }}</p>
            <div class="meta-section">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>截止日期：{{ formatDate(project.deadline) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>负责人：{{ project.manager }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>团队成员：{{ project.teamMembers.length }}人</span>
              </div>
            </div>
            <div class="team-members">
              <el-avatar-group :max="3" size="small">
                <el-tooltip 
                  v-for="member in project.teamMembers" 
                  :key="member.id" 
                  :content="member.name" 
                  placement="top"
                >
                  <el-avatar :src="member.avatar" />
                </el-tooltip>
              </el-avatar-group>
            </div>
            <div class="progress-section">
              <div class="progress-header">
                <span>完成进度</span>
                <span class="progress-percentage">{{ project.progress }}%</span>
              </div>
              <el-progress 
                :percentage="project.progress" 
                :status="getProgressStatus(project.progress)" 
                :stroke-width="10"
              />
            </div>
            <div class="card-footer">
              <el-button type="primary" size="small" @click="viewProjectDetail(project.id)">查看详情</el-button>
              <el-button size="small" @click="editProject(project)">编辑</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 项目列表 - 表格视图 -->
    <div class="list-view" v-else>
      <el-table :data="sortedProjects" style="width: 100%" border stripe>
        <el-table-column prop="name" label="项目名称" width="200">
          <template #default="scope">
            <div class="project-name-cell">
              <el-tag :type="getStatusType(scope.row.status)" size="small" effect="dark">
                {{ scope.row.statusText }}
              </el-tag>
              <span class="project-name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="manager" label="负责人" width="120" />
        <el-table-column prop="deadline" label="截止日期" width="120" />
        <el-table-column label="团队成员" width="150">
          <template #default="scope">
            <el-avatar-group :max="3" size="small">
              <el-avatar 
                v-for="member in scope.row.teamMembers" 
                :key="member.id" 
                :src="member.avatar" 
                :size="28"
              />
            </el-avatar-group>
            <span class="member-count">{{ scope.row.teamMembers.length }}人</span>
          </template>
        </el-table-column>
        <el-table-column label="进度" width="200">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.progress" 
              :status="getProgressStatus(scope.row.progress)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewProjectDetail(scope.row.id)">详情</el-button>
            <el-button size="small" @click="editProject(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑项目对话框 -->
    <el-dialog 
      v-model="showDialog" 
      :title="isEditing ? '编辑项目' : '新增项目'"
      width="600px"
    >
      <el-form :model="newProject" label-width="100px" :rules="projectRules" ref="projectForm">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="newProject.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input 
            v-model="newProject.description" 
            type="textarea" 
            rows="3" 
            placeholder="请输入项目描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="newProject.manager" placeholder="请输入负责人姓名"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker v-model="newProject.startDate" type="date" placeholder="选择开始日期" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="deadline">
              <el-date-picker v-model="newProject.deadline" type="date" placeholder="选择截止日期" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="newProject.status" placeholder="请选择项目状态" style="width: 100%">
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-slider v-model="newProject.progress" :format-tooltip="formatProgress" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="submitProject" :loading="submitting">
          {{ isEditing ? '保存修改' : '创建项目' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog 
      v-model="showDeleteConfirm" 
      title="删除项目" 
      width="400px"
      destroy-on-close
    >
      <div class="delete-confirm">
        <i class="el-icon-warning warning-icon"></i>
        <p>确定要删除项目 "{{ projectToDelete?.name }}" 吗？</p>
        <p class="warning-text">此操作不可恢复！</p>
      </div>
      <template #footer>
        <el-button @click="showDeleteConfirm = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleting">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 状态更改对话框 -->
    <el-dialog 
      v-model="showStatusDialog" 
      title="更改项目状态" 
      width="400px"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="更改为" prop="newStatus">
          <el-select v-model="statusForm.newStatus" placeholder="选择新状态" style="width: 100%">
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmStatusChange" :loading="changingStatus">
          确认更改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { Search, Calendar, User } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

// 视图模式
const viewMode = ref('card');
const sortBy = ref('createDate');

// 状态筛选
const status = ref('');
// 搜索关键词
const searchQuery = ref('');
// 控制对话框显示
const showDialog = ref(false);
const showDeleteConfirm = ref(false);
const showStatusDialog = ref(false);
// 编辑模式标志
const isEditing = ref(false);
// 表单提交状态
const submitting = ref(false);
const deleting = ref(false);
const changingStatus = ref(false);

// 项目表单引用
const projectForm = ref(null);

// 表单校验规则
const projectRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  deadline: [
    { type: 'date', required: true, message: '请选择截止日期', trigger: 'change' }
  ]
};

// 新增/编辑项目的表单数据
const newProject = ref({
  id: null,
  name: '',
  description: '',
  manager: '',
  deadline: '',
  startDate: '',
  status: 'active',
  statusText: '进行中',
  progress: 0,
  teamMembers: []
});

// 状态变更表单
const statusForm = reactive({
  projectId: null,
  currentStatus: '',
  newStatus: ''
});

// 待删除的项目
const projectToDelete = ref(null);

// 项目列表数据
const projects = ref([
  {
    id: 1,
    name: '企业官网重构',
    description: '对公司官网进行全面改版，提升用户体验和转化率',
    manager: '张三',
    startDate: '2023-01-15',
    deadline: '2023-05-30',
    status: 'active',
    statusText: '进行中',
    progress: 65,
    teamMembers: [
      { id: 1, name: '张三', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
      { id: 2, name: '李四', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
      { id: 3, name: '王五', avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' },
      { id: 4, name: '赵六', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' }
    ]
  },
  {
    id: 2,
    name: '移动端APP开发',
    description: '开发公司产品的移动应用，支持iOS和Android平台',
    manager: '李四',
    startDate: '2023-02-10',
    deadline: '2023-06-20',
    status: 'active',
    statusText: '进行中',
    progress: 40,
    teamMembers: [
      { id: 2, name: '李四', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
      { id: 5, name: '钱七', avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' }
    ]
  },
  {
    id: 3,
    name: '产品数据分析系统',
    description: '构建产品数据分析平台，提供报表和数据可视化功能',
    manager: '王五',
    startDate: '2022-12-05',
    deadline: '2023-04-15',
    status: 'completed',
    statusText: '已完成',
    progress: 100,
    teamMembers: [
      { id: 3, name: '王五', avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' },
      { id: 6, name: '孙八', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
      { id: 7, name: '周九', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' }
    ]
  },
  {
    id: 4,
    name: '后台管理系统',
    description: '开发内部使用的后台管理系统，提高工作效率',
    manager: '赵六',
    startDate: '2023-01-20',
    deadline: '2023-07-10',
    status: 'paused',
    statusText: '已暂停',
    progress: 30,
    teamMembers: [
      { id: 4, name: '赵六', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
      { id: 8, name: '吴十', avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png' }
    ]
  }
]);

// 根据搜索条件筛选项目
const filteredProjects = computed(() => {
  return projects.value.filter(project => {
    // 状态筛选
    if (status.value && project.status !== status.value) {
      return false;
    }
    
    // 关键词搜索
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase();
      return project.name.toLowerCase().includes(query) || 
             project.description.toLowerCase().includes(query);
    }
    
    return true;
  });
});

// 排序后的项目列表
const sortedProjects = computed(() => {
  const filtered = [...filteredProjects.value];
  
  switch (sortBy.value) {
    case 'deadline':
      return filtered.sort((a, b) => new Date(a.deadline) - new Date(b.deadline));
    case 'progress':
      return filtered.sort((a, b) => b.progress - a.progress);
    case 'createDate':
    default:
      return filtered.sort((a, b) => new Date(b.startDate) - new Date(a.startDate));
  }
});

// 获取进行中项目数量
const getActiveProjectsCount = () => {
  return projects.value.filter(p => p.status === 'active').length;
};

// 获取已完成项目数量
const getCompletedProjectsCount = () => {
  return projects.value.filter(p => p.status === 'completed').length;
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 'active': return 'primary';
    case 'completed': return 'success';
    case 'paused': return 'warning';
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active': return '进行中';
    case 'completed': return '已完成';
    case 'paused': return '已暂停';
    default: return '未知状态';
  }
};

// 获取进度条状态
const getProgressStatus = (progress) => {
  if (progress >= 100) return 'success';
  if (progress > 70) return '';
  if (progress > 30) return 'warning';
  return 'exception';
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化进度提示
const formatProgress = (val) => {
  return `${val}%`;
};

// 提交项目表单
const submitProject = () => {
  projectForm.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    
    try {
      // 克隆表单数据
      const projectData = { ...newProject.value };
      
      // 设置状态文本
      projectData.statusText = getStatusText(projectData.status);
      
      if (isEditing.value) {
        // 更新现有项目
        const index = projects.value.findIndex(p => p.id === projectData.id);
        if (index !== -1) {
          // 保留团队成员信息
          projectData.teamMembers = projects.value[index].teamMembers;
          projects.value[index] = projectData;
          ElMessage.success('项目更新成功！');
        }
      } else {
        // 创建新项目
        projectData.id = Date.now(); // 模拟生成ID
        projectData.teamMembers = []; // 初始化空团队
        projects.value.unshift(projectData);
        ElMessage.success('项目创建成功！');
      }
      
      // 重置并关闭表单
      resetForm();
    } catch (error) {
      console.error('提交项目出错:', error);
      ElMessage.error('操作失败，请重试');
    } finally {
      submitting.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  showDialog.value = false;
  isEditing.value = false;
  
  // 重置表单数据
  newProject.value = {
    id: null,
    name: '',
    description: '',
    manager: '',
    deadline: '',
    startDate: '',
    status: 'active',
    statusText: '进行中',
    progress: 0,
    teamMembers: []
  };
  
  // 重置表单验证
  if (projectForm.value) {
    projectForm.value.resetFields();
  }
};

// 取消对话框
const cancelDialog = () => {
  ElMessageBox.confirm('确定取消操作吗？未保存的数据将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '返回编辑',
    type: 'warning'
  }).then(() => {
    resetForm();
  }).catch(() => {});
};

// 编辑项目
const editProject = (project) => {
  isEditing.value = true;
  newProject.value = { ...project };
  showDialog.value = true;
};

// 删除项目
const deleteProject = (project) => {
  projectToDelete.value = project;
  showDeleteConfirm.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!projectToDelete.value) return;
  
  deleting.value = true;
  
  try {
    const index = projects.value.findIndex(p => p.id === projectToDelete.value.id);
    if (index !== -1) {
      projects.value.splice(index, 1);
      ElMessage.success('项目已删除');
    }
  } catch (error) {
    console.error('删除项目出错:', error);
    ElMessage.error('删除失败，请重试');
  } finally {
    deleting.value = false;
    showDeleteConfirm.value = false;
    projectToDelete.value = null;
  }
};

// 更改项目状态
const changeStatus = (project) => {
  statusForm.projectId = project.id;
  statusForm.currentStatus = project.status;
  statusForm.newStatus = project.status;
  showStatusDialog.value = true;
};

// 确认状态变更
const confirmStatusChange = async () => {
  if (!statusForm.projectId || statusForm.currentStatus === statusForm.newStatus) {
    showStatusDialog.value = false;
    return;
  }
  
  changingStatus.value = true;
  
  try {
    const index = projects.value.findIndex(p => p.id === statusForm.projectId);
    if (index !== -1) {
      projects.value[index].status = statusForm.newStatus;
      projects.value[index].statusText = getStatusText(statusForm.newStatus);
      
      // 如果完成，设置进度为100%
      if (statusForm.newStatus === 'completed' && projects.value[index].progress < 100) {
        projects.value[index].progress = 100;
      }
      
      ElMessage.success('项目状态已更新');
    }
  } catch (error) {
    console.error('更新状态出错:', error);
    ElMessage.error('状态更新失败，请重试');
  } finally {
    changingStatus.value = false;
    showStatusDialog.value = false;
  }
};

// 查看项目详情
const viewProjectDetail = (projectId) => {
  router.push(`/projects/detail/${projectId}`);
};

onMounted(() => {
  // 可以在这里从API加载项目数据
  console.log('项目管理页面已加载');
});
</script>

<style lang="scss" scoped>
.projects-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .title-section {
      display: flex;
      align-items: center;
      gap: 40px;

      .page-title {
        margin: 0;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }

      .stats-section {
        display: flex;
        gap: 20px;
        
        .stat-item {
          display: flex;
          flex-direction: column;
          
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #409EFF;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .filter-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;
    align-items: center;
    background-color: #f5f7fa;
    padding: 14px 20px;
    border-radius: 8px;
    
    .search-section {
      flex: 1;
      margin-right: 20px;
      
      .search-input {
        width: 100%;
      }
    }
    
    .filter-section {
      display: flex;
      gap: 12px;
      align-items: center;
      
      .filter-select {
        width: 140px;
      }
      
      .view-toggle {
        margin-left: 12px;
        
        .active {
          color: #409EFF;
          background-color: #ecf5ff;
        }
      }
    }
  }
  
  .project-list {
    margin-bottom: 20px;
    
    .project-card {
      height: 100%;
      margin-bottom: 20px;
      transition: all 0.3s;
      border-radius: 8px;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
      }
      
      &.status-active {
        border-top: 3px solid #409EFF;
      }
      
      &.status-completed {
        border-top: 3px solid #67C23A;
      }
      
      &.status-paused {
        border-top: 3px solid #E6A23C;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          flex-direction: column;
          gap: 6px;
          
          .project-title {
            margin: 8px 0 0;
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
        }
      }
      
      .card-content {
        .description {
          margin: 10px 0;
          color: #606266;
          font-size: 14px;
          min-height: 40px;
        }
        
        .meta-section {
          margin: 16px 0;
          
          .meta-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 8px;
            color: #606266;
            font-size: 13px;
            
            .el-icon {
              color: #909399;
            }
          }
        }
        
        .team-members {
          margin: 16px 0;
        }
        
        .progress-section {
          margin: 16px 0;
          
          .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 6px;
            font-size: 14px;
            color: #606266;
            
            .progress-percentage {
              font-weight: bold;
            }
          }
        }
        
        .card-footer {
          display: flex;
          gap: 10px;
          margin-top: 20px;
        }
      }
    }
  }
  
  .list-view {
    .project-name-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .project-name {
        margin-left: 8px;
        font-weight: 500;
      }
    }
    
    .member-count {
      margin-left: 8px;
      font-size: 12px;
      color: #909399;
    }
  }
  
  .delete-confirm {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      font-size: 48px;
      color: #E6A23C;
      margin-bottom: 16px;
    }
    
    p {
      margin: 8px 0;
      font-size: 16px;
    }
    
    .warning-text {
      color: #F56C6C;
      font-weight: bold;
    }
  }
}
</style>